package org.swan.web.user.service.impl;

import org.springframework.stereotype.Service;
import org.stream.tool.db.ADOConnection;
import org.swan.web.exception.BusinessCode;
import org.swan.web.exception.BusinessException;
import org.swan.web.user.bean.UserExtensionBean;
import org.swan.web.user.mapper.UserExtensionMapper;
import org.swan.web.user.service.UserExtensionService;

import java.util.List;
import java.util.Optional;

@Service
public class UserExtensionServiceImpl implements UserExtensionService {

    @Override
    public Optional<UserExtensionBean> getUserExtensionById(long id) {
        if (id == -1L)
            return Optional.of(UserExtensionBean.SAMPLE);
        return ADOConnection.runTask(factory -> factory.getMapper(UserExtensionMapper.class).getById(id), Optional.class);
    }

    @Override
    public long addUserExtension(UserExtensionBean userExtensionBean) {
        long result = ADOConnection.runTask(factory -> factory.getMapper(UserExtensionMapper.class).add(userExtensionBean), Long.class);
        return result;
    }

    @Override
    public UserExtensionBean updateUserExtension(UserExtensionBean userExtensionBean) {
        getUserExtensionById(userExtensionBean.getUserExtensionId()).orElseThrow(() -> new BusinessException(BusinessCode.USER_EXTENSION_DO_NOT_EXIST, userExtensionBean.getUserExtensionId()));
        ADOConnection.runTask(factory -> factory.getMapper(UserExtensionMapper.class).updateById(userExtensionBean), Long.class);
        return getUserExtensionById(userExtensionBean.getUserExtensionId()).get();
    }

    @Override
    public UserExtensionBean deleteUserExtensionById(long userExtensionId) {
        UserExtensionBean userExtensionBean = getUserExtensionById(userExtensionId).orElseThrow(() -> new BusinessException(BusinessCode.USER_EXTENSION_DO_NOT_EXIST, userExtensionId));
        ADOConnection.runTask(factory -> factory.getMapper(UserExtensionMapper.class).deleteById(userExtensionId), Long.class);
        return userExtensionBean;
    }

    @Override
    public List<UserExtensionBean> list(int offset, int rows) {
        return ADOConnection.runTask(factory -> factory.getMapper(UserExtensionMapper.class).list(offset, rows), List.class);
    }


}
